<?php

/*我的控制器*/

namespace App\Http\Controllers\Wap;

use App\Models\AdminParam;
use App\Models\Order;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class MyController extends WapController
{

    // 我的页面
    public function index(Request $request, User $user)
    {
        $uid = $request->get('user')->id;
        $user = $user->find($uid);
        return $this->success($user);

    }

    //我的订单
    public function myOrders(Request $request, Order $order)
    {
        $uid = $request->get('user')->id;
        $my_order = $order::with('items')
            ->where('user_id', $uid)
            ->whereNotNull('paid_at')
            ->get();

        return $this->success($my_order);
    }


    // 查询是否可以领取优惠券
    public function getCoupon(Request $request, AdminParam $model){
        $params = $model->first();
        if(!$params){
            return $this->message('没有优惠券');
        }
        if($params->coupon == 0){
            return $this->message('没有优惠券');
        }

        // 查询是否已领取过优惠券
        if ($request->hasHeader('authorization') === false) {
            return response()->json([
                'status' => 'success',
                'code' => 203,
                'message' => 'Missing "Authorization" header'
            ])->setStatusCode(203);
        }
        $header = $request->header('authorization');
        $token = trim(preg_replace('/^(?:\s+)?Bearer\s/', '', $header));
        if(\Cache::has($token)){
            $user = \Cache::get($token);
            $user = $user->find($user->id);
            if($user->coupon){
                return $this->message('已领取过了');
            }
        }

        return $this->success(['coupon'=> $params->coupon]);
    }

    // 领取优惠券
    public function receiveCoupon(Request $request, AdminParam $model){
        $user = $request->get('user');
        $coupon = $request->post('coupon');
        $params = $model->first();
        if($coupon != $params->coupon){
            return $this->message('数据有误！');
        }
        $user = $user->find($user->id);
        if($user->coupon){
            return $this->message('已领取过了');
        }
        $user->coupon = $params->coupon;
        $user->coupon_at = Carbon::now();
        $user->save();
        return $this->success('领取成功');

    }

}
